package com.example.cinema.controller;

import com.example.cinema.entity.User;
import com.example.cinema.mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/29
 * Email haijunzhou@hnit.edu.cn
 */
@Component
@ServerEndpoint("/talk/{id}")
@Slf4j
public class TalkWebSocket {

    // 群聊
    static HashSet<Session> sessions = new HashSet<>();


    static UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        TalkWebSocket.userMapper = userMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) throws IOException {
        log.info(id + " 上线了!");
        User user = userMapper.selectById(id);
        session.getUserProperties().put("user",user);
        sessions.add(session);
        send(new MsgInfo(sessions.stream()
                .map(s->(User)s.getUserProperties().get("user"))
                .collect(Collectors.toList()),
                user,
                "上线了!"));
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        User user = (User)session.getUserProperties().get("user");
        log.info(user.getName() + " 下线了!");
        sessions.remove(session);
        send(new MsgInfo(sessions.stream()
                .map(s->(User)s.getUserProperties().get("user"))
                .collect(Collectors.toList()),
                user,
                "下线了!"));
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        User user = (User)session.getUserProperties().get("user");
        log.info(user.getName() + " 说: " + message);
        send(new MsgInfo(null,
                user,
                message));
    }

    public void send(MsgInfo msgInfo) throws IOException {
        for (Session s : sessions) {
            String message = new ObjectMapper().writeValueAsString(msgInfo);
            s.getBasicRemote().sendText(message);
        }
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class MsgInfo{
    // 在线用户列表
    List<User> onlines;
    // 发送人
    User user;
    // 文字消息
    String message;
}
